import {
	CONFIG
} from '@/config/app'
import {
	app
} from '../main'

/**
 * 发送请求
 */
function baseRequest(url, method, data, {
	noAuth = false,
	noVerify = false
}, params) {
	let Url = CONFIG.HTTP_REQUEST_URL,
		header = CONFIG.HEADER
	if (params != undefined) {
		header = CONFIG.HEADERPARAMS
	}
	if (!noAuth) {
		//登录过期自动登录
	}

	// TODO 补个 header 多租户
	if (url.indexOf('app-api') >= 0) {
		header = {
			...header,
		}
		header['tenant-id'] = 1
	}
	if (!noAuth) {
		if (uni.getStorageSync('token')) {
			// header[TOKENNAME] = store.state.app.token;
			header['Authorization'] = 'Bearer ' + uni.getStorageSync('token')
			//terminal h5端支付
			header['terminal'] = '20'
		}
	}

	return new Promise((reslove, reject) => {
		uni.request({
			// url: url.indexOf('app-api') < 0 ? Url + '/api/front/' + url
			url: url.indexOf('app-api') < 0 ?
				Url + url // : 'http://yunai.natapp1.cc/' + url, // TODO 芋艿：搞个 url 的配置
				// : 'http://192.168.0.142:48080/' + url, // TODO 芋艿：搞个 url 的配置
				:
				Url + url, // TODO 芋艿：搞个 url 的配置
			// : 'http://api-dashboard.yudao.iocoder.cn/' + url, // TODO 芋艿：搞个 url 的配置
			method: method || 'GET',
			header: header,
			data: data || {},
			success: res => {
				if (noVerify) reslove(res.data, res)
				else if (res.data.code === 200 || res.data.code === 0) {

					reslove(res.data, res)
				} else if ([410000, 410001, 410002, 401].indexOf(res.data.code) !== -1) {
					uni.removeStorageSync('token')
					uni.reLaunch({
						url: '/pages/login/login',
					})
				} else {
					uni.showToast({
						title: res.data.msg,
						icon: 'none',
						duration: 2000,
					})
				}
				// reject(res.data.msg || res.data.message || '系统错误');
			},
			fail: msg => {
				reject('请求失败')
			},
		})
	})
}

const request = {}

;
['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach(method => {
	request[method] = (api, data, opt, params) => baseRequest(api, method, data, opt || {}, params)
})

export default request